package engine

import "code.google.com/p/go8/display"

type Sizer interface {
	Size() (w, h int)
}

type CanvasSizer interface {
	CanvasSize() (w, h int)
}

type ImageCenterer struct{}

func NewImageCenterer() ImageCenterer {
	return ImageCenterer{}
}

func (_ ImageCenterer) Center(image Sizer, canvas CanvasSizer) display.Rect {
	cw, ch := canvas.CanvasSize()
	iw, ih := image.Size()
	ratio := canvasToImageRatio(cw, ch, iw, ih)

	if ratio == 0 {
		return display.Rect{0, 0, cw, ch}
	} else if ratio > 0 {
		return fullHeightRect(cw, ch, iw, ih)
	} else {
		return fullWidthRect(cw, ch, iw, ih)
	}
}

func canvasToImageRatio(cw, ch, iw, ih int) float32 {
	screenRatio := float32(cw) / float32(ch)
	imageRatio := float32(iw) / float32(ih)
	return screenRatio - imageRatio
}

func fullHeightRect(cw, ch, iw, ih int) display.Rect {
	w := int(float32(iw) * float32(ch) / float32(ih))
	x := (cw - w) / 2
	return display.Rect{x, 0, w, ch}
}

func fullWidthRect(cw, ch, iw, ih int) display.Rect {
	h := int(float32(ih) * float32(cw) / float32(iw))
	y := (ch - h) / 2
	return display.Rect{0, y, cw, h}
}
